package Index;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;

import core.*;
import repository.Repository;
import fileoperation.*;
import gitobject.*;

public class index implements Serializable {
    private static final String indexPath = Repository.getGitDir() + File.separator + "index";
    private static HashMap<String, Blob> hashMap = new HashMap<>();


    public static void indexOffile() throws IOException, ClassNotFoundException {
        //从文件中读取index
        File file = new File(indexPath);
        FileInputStream fileIS = new FileInputStream(file);
        ObjectInputStream objIS = new ObjectInputStream(fileIS);
        hashMap = (HashMap<String, Blob>) objIS.readObject();
        fileIS.close();
        objIS.close();
    }

    public static String getIndexPath() {
        return indexPath;
    }

    public static HashMap<String, Blob> getHashMap() {
        return hashMap;
    }

    public static void addToIndex(File file) throws Exception {
        //把文件加入到index当中
        Blob blob = new Blob(file);
        //获取文件在worktree的相对路径
        String relativePath = getRelativePath(file);
        hashMap.put(relativePath, blob);
        writeIndex();
    }

    public static void resetIndex(File file) throws Exception {
        //根据工作区文件添加index，需先清空index文件
        if (file.isFile()) {
            addToIndex(file);
        } else {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (!files[i].getName().equals(".jit")) {
                    resetIndex(files[i]);
                }
            }
        }
    }

    public static void deleteFromIndex(File file) throws Exception {
        //从index中删除掉file
        String relativePath = getRelativePath(file);
        hashMap.remove(relativePath);
        writeIndex();
        File file = new File(Repository.getWorkTree() + File.separator + filePath);
        deleteFromIndex(file);
    }

    public static String getRelativePath(File file) {
        //获取文件的相对路径relativePath
        return file.getPath().replace(Repository.getWorkTree() + File.separator, "");
    }
    
    public static void writeIndex() throws IOException {
        //将index写入文件
        FileOutputStream fileOS = new FileOutputStream(indexPath);
        ObjectOutputStream ObjOS = new ObjectOutputStream(fileOS);
        ObjOS.writeObject(hashMap);
        fileOS.close();
        ObjOS.close();
    }

    public static Boolean checkIsSame(GitObject tmpObject, String filename) throws Exception {
        //判断commit区(objects文件夹)下是否有当前index区同样文件
        String indexPath = Repository.getGitDir() + File.separator + "index";
        String filePath = indexPath + File.separator + tmpObject.toString() + " " + filename;
        String objectsPath = Repository.getGitDir() + File.separator + "objects";

        String key = new Tree(new File(indexPath)).getKey();
        
        //如果工作区中的文件内容和当前commit中所保存的文件内容一致（没有修改），
        //那么不将其add入暂存区中。
        for(String subfile: new File(objectsPath).list()) {
            Commit existCommit = null;
            String[] tmp = subfile.split(" ");

            if(!tmp[0].equals("040000")) {
                existCommit = Commit.deserialize(subfile, 1); //反序列化commit

                if(key.equals(existCommit.getTree())) { //比较commit.tree与当前index的tree的key

                    System.gc();
                    FileDeletion.deleteFile(filePath);//删除之前临时添加
                    System.gc();

                    System.out.println("[objects] and [index]: No changed files, please check.");
                    return false;//same
                }
            }
        }
        return true;//Not same
    }
}